#include "TimerOne.h"

/*
Most Arduino boards have two external interrupts: 
 - 0 (on digital pin 2) 
 - 1 (on digital pin 3)
The Arduino Mega has an additional four:
 - 2 (pin 21)
 - 3 (pin 20)
 - 4 (pin 19)
 - 5 (pin 18)
 */

/*
Four contstants modes are predefined as valid values:
 - LOW to trigger the interrupt whenever the pin is low,
 - CHANGE to trigger the interrupt whenever the pin changes value
 - RISING to trigger when the pin goes from low to high,
 - FALLING for when the pin goes from high to low.
*/

int pin = 13;
volatile int state = LOW;
int count;

void setup()
{
  pinMode(pin, OUTPUT);
//  attachInterrupt(0, interrupt_handler_orig, RISING);
  attachInterrupt(0, interrupt_handler_debounce, RISING);
  
  Serial.begin(57600); 

  count = 0;
  
  Timer1.initialize(1000000);         // initialize timer1, and set a 1 second period
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt

}

void loop()
{
  digitalWrite(pin, state);


  Serial.print("Interrupt received (count = ");
  Serial.print(count);
  Serial.print(")\n");
  delay(3000);

}


void callback()
{
  Serial.print(".");
}

void interrupt_handler_orig()
{
  state = !state; 
  count++;

//  delay(200); // try to debounce, but this doesn't work !
}

void interrupt_handler_debounce()
{
  static unsigned long last_interrupt_time = 0;
  unsigned long interrupt_time = millis();
  // If interrupts come faster than 200ms, assume it's a bounce and ignore
  if (interrupt_time - last_interrupt_time > 200)
  {
  	state = !state; 
	count++;
  }
  last_interrupt_time = interrupt_time;
} 


